package com.huafv.flyauth.security;

import com.huafv.flyauth.core.redis.RedisCache;
import com.huafv.flyauth.security.handle.LoginFailureHandler;
import com.huafv.flyauth.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }


        if (JwtUtil.checkToken("huafv", token, "fly")) {
            String username = (String) JwtUtil.getClaims("huafv", token).get("user");
            LoginUser loginUser = redisCache.getCacheObject("login:" + username);
            if (Objects.isNull(loginUser)) {
//                throw new RuntimeException("login err");
                loginFailureHandler.onAuthenticationFailure(request, response,null);
                return;
            }

            //  获取权限信息封装到 Authentication 中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

            //  封装 Authentication 对象存入 SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }


        filterChain.doFilter(request, response);
    }
}
